<template>
  <div>
    <TypeNav :firstShowSort="false" :hovorShowSort="true"></TypeNav>

    <!--list-content-->
    <div class="main">
      <div class="py-container">
        <!--bread-->
        <div class="bread">
          <ul class="fl sui-breadcrumb">
            <li>
              <a href="#">全部结果</a>
            </li>
          </ul>
          <ul class="fl sui-tag">
            <!-- 分类 -->
            <li class="with-x" v-if="$route.query.categoryName">
              {{ $route.query.categoryName
              }}<i @click="removeBread('categoryName')">×</i>
            </li>
            <!-- 关键字 -->
            <li class="with-x" v-if="$route.params.keyword">
              {{ $route.params.keyword
              }}<i @click="removeBread('keyword')">×</i>
            </li>
            <!-- 品牌 -->
            <li class="with-x" v-if="params.trademark">
              {{ params.trademark.split(':')[1]
              }}<i @click="removeBread('trade')">×</i>
            </li>
            <!-- 商品属性 -->
            <li class="with-x" v-for="data in params.props" :key="data">
              {{ data.split(':')[2]
              }}<i @click="removeBread('attr', data)">×</i>
            </li>
          </ul>
        </div>

        <SearchSelector
          @eventTrade="dealTrade"
          @eventAttr="dealAttr"
        ></SearchSelector>

        <!--details-->
        <div class="details clearfix">
          <div class="sui-navbar">
            <div class="navbar-inner filter">
              <!-- 综合|价格排序的地方 -->
              <ul class="sui-nav">
                <li :class="{ active: isOne }" @click="changeSort('1')">
                  <a
                    >综合<span v-show="isOne && isAsc">⬆</span
                    ><span v-show="isOne && !isAsc">⬇</span></a
                  >
                </li>
                <li :class="{ active: !isOne }" @click="changeSort('2')">
                  <a
                    >价格<span v-show="!isOne && isAsc">⬆</span
                    ><span v-show="!isOne && !isAsc">⬇</span></a
                  >
                </li>
                <li>
                  <a>销量</a>
                </li>
                <li>
                  <a>新品</a>
                </li>
                <li>
                  <a>评价</a>
                </li>
              </ul>
            </div>
          </div>
          <!-- 商品展示区域 -->
          <div class="goods-list">
            <ul class="yui3-g">
              <li class="yui3-u-1-5" v-for="goods in goodsList" :key="goods.id">
                <div class="list-wrap">
                  <div class="p-img">
                    <!--商品的图片:需要路由跳转的时候,携带商品的ID 跳转商品详情页-->
                    <router-link :to="`/detail/${goods.id}`">
                      <img v-lazy="goods.defaultImg" />
                    </router-link>
                  </div>
                  <div class="price">
                    <strong>
                      <em>¥</em>
                      <i>{{ ' ' + goods.price }}</i>
                    </strong>
                  </div>
                  <div class="attr">
                    <a :title="goods.title">{{ goods.title }}</a>
                  </div>
                  <div class="commit">
                    <i class="command">已有<span>2000</span>人评价</i>
                  </div>
                  <div class="operate">
                    <a
                      @click="addShopCar(goods)"
                      class="sui-btn btn-bordered btn-danger"
                      >加入购物车</a
                    >
                    <a href="javascript:void(0);" class="sui-btn btn-bordered"
                      >收藏</a
                    >
                  </div>
                </div>
              </li>
            </ul>
          </div>
          <!-- 分页的地方 -->
          <Pagenation
            :continuousPageNum="3"
            :showNum="params.pageSize"
            :totalNum="totalNum"
            @pageNumChange="pagechange"
          ></Pagenation>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapState } from 'vuex'
import SearchSelector from './SearchSelector/index.vue'
import Pagenation from '../../components/Pagenation/index.vue'
export default {
  components: { SearchSelector, Pagenation },
  computed: {
    ...mapGetters(['goodsList']),
    ...mapState({
      totalNum(state) {
        return state.search.searchList.total
      }
    }),
    isOne() {
      return this.params.order.split(':')[0] == 1
    },
    isAsc() {
      return this.params.order.split(':')[1] == 'asc'
    }
  },
  watch: {
    $route: {
      deep: true,
      immediate: true,
      handler(newVal) {
        if (newVal.path.includes('/search')) {
          this.getSearchList()
        }
      }
    }
  },
  data() {
    return {
      params: {
        trademark: '',
        props: [],
        order: '1:asc',
        pageNo: 1,
        pageSize: 10
      }
    }
  },
  methods: {
    //商品搜索
    getSearchList() {
      // 合并参数
      let temp = {}
      Object.assign(temp, this.params, this.$route.query, this.$route.params)
      this.$store.dispatch('getGoodsList', temp)
    },
    //删除面包屑
    removeBread(tag, data) {
      if (!tag) return

      //ruote改变会被监听到,会去跟新数据,同时面包屑也会隐藏
      if (tag === 'categoryName') {
        if (this.$route.query.categoryName) this.$route.query.categoryName = ''
        if (this.$route.query.category1Id) this.$route.query.category1Id = ''
        if (this.$route.query.category2Id) this.$route.query.category2Id = ''
        if (this.$route.query.category3Id) this.$route.query.category3Id = ''

        //这一步是为了改变url
        this.$router.push({
          name: 'search',
          params: this.$route.params
        })
      }

      //ruote改变会被监听到,会去跟新数据,同时面包屑也会隐藏
      if (tag === 'keyword') {
        if (this.$route.params.keyword) this.$route.params.keyword = ''

        //删除搜索框中的keyword
        this.$bus.$emit('removeKeyword')

        //这一步是为了改变url
        this.$router.push({
          name: 'search',
          query: this.$route.query
        })
      }

      if (tag === 'trade') {
        // 将params数据改变
        this.params.trademark = ''
        //发起请求
        this.getSearchList()
      }

      if (tag === 'attr') {
        // 将params数据改变
        this.params.props.splice(this.params.props.indexOf(data), 1)
        //发起请求
        this.getSearchList()
      }
    },
    //点击品牌
    dealTrade(trade) {
      let str = `${trade.tmId}:${trade.tmName}`
      if (str !== this.params.trademark) {
        //添加到请求参数对象
        this.params.trademark = str
        //发起请求
        this.getSearchList()
      }
    },
    //点击商品属性
    dealAttr(attr, info) {
      //添加到请求参数对象
      let str = `${attr.attrId}:${attr.attrName}:${info}`
      if (this.params.props.indexOf(str) === -1) {
        this.params.props.push(str)
        //发起请求
        this.getSearchList()
      }
    },
    // 更改排序方式
    changeSort(arg) {
      // 当前的排序方式
      let sort1 = this.params.order.split(':')[0]
      let sort2 = this.params.order.split(':')[1]

      if (arg == sort1) {
        //改变升降
        this.params.order = `${sort1}:${sort2 == 'asc' ? 'desc' : 'asc'}`
      } else {
        //改变价格|综合
        this.params.order = `${sort1 == '1' ? '2' : '1'}:${sort2}`
      }

      //发起请求
      this.getSearchList()
    },
    // 页码改变
    pagechange(num) {
      this.params.pageNo = num
      // 发送请求
      this.getSearchList()
    },
    //添加购物车
    async addShopCar(data) {
      let result = await this.$API.reqAddOrChangeShop(data.id, 1)
      if (result.code == 200) {
        // 将该商品的信息存储回话,一会成功组件使用
        sessionStorage.setItem(
          'SHOPGOODSINFO',
          JSON.stringify({
            skuDefaultImg: data.defaultImg,
            skuName: data.tmName
          })
        )
        sessionStorage.setItem('BUYATTR', JSON.stringify([]))
        // 跳转到购买成功页
        this.$router.push('/addcarsuccess/' + 1)
      } else {
        alert(result.message)
      }
    }
  },

  mounted() {
    console.log('search 组件 挂载')
  }
}
</script>

<style></style>
